﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using CE.Configuration;
using CE.Global;
using CE.User;
using CE.Image;
using CE.Security;
public partial class car_insurance_set_insurance_reminder : MyLanguageBasePage
{
    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Master.Page.Title = Resources.Title.SetInsuranceReminderTitle;

        LiteralControl newln = new LiteralControl(Environment.NewLine);
        HtmlMeta language = new HtmlMeta();
        language.Name = "language";
        language.Content = Resources.Title.PageLanguage;
        if (!IsPostBack)
        {
            lblSetInsMessage.Visible = false;
            //GetCookies();
            Session["UMMSG"] = null;
            txtEmail.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtEmail.ClientID + "','" + rfvEmail.ClientID + "','" + revEmail.ClientID + "');");
            txtName.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtName.ClientID + "','" + rfvName.ClientID + "','" + revName.ClientID + "');");
            txtMobile.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtMobile.ClientID + "','" + rfvMobile.ClientID + "','" + revMobile.ClientID + "');");
            ddlCarMonth.Attributes.Add("onblur", "ShowValidationEffect('" + ddlCarMonth.ClientID + "','" + rfvCarMonth.ClientID + "');");
            Page.Form.DefaultButton = btnSetReminder.UniqueID;
            if (Session[CE.Global.General.UserEmail] != null && Session[CE.Global.General.UserName] != null && Session[CE.Global.General.UserPhoneNo] != null)
            {
                txtName.Text = Session[CE.Global.General.UserName].ToString();
                txtEmail.Text = Session[CE.Global.General.UserEmail].ToString();
                txtMobile.Text = Session[CE.Global.General.UserPhoneNo].ToString();
            }
            if (Session[CE.Global.General.IsAcceptTC] != null)
            {
                checkIsAgreement.Checked = true;
                if (Session[CE.Global.General.IsAcceptTC].ToString() != "1")
                {
                    checkIsAgreement.Checked = false;
                }
            }
        }
    }

    protected void btnSetReminder_Click(object sender, EventArgs e)
    {
        lblSetInsMessage.Visible = false;
        ChangeValidationEffectServerSide("reminder");
        Page.Validate("reminder");
        if (Page.IsValid)
        {
            #region Check Customer Account
            Int64 _userId = 0;
            Account _useraccount = new Account();
            AccountDB _useraccountdb = new AccountDB();

            _useraccount = _useraccountdb.GetUserAccount(EmailAddress, Convert.ToInt32(CE.Global.CEUserType.Customer));
            //_useraccount = _useraccountdb.GetUserAccount(EmailAddress, MobileNumber, Convert.ToInt32(CE.Global.CEUserType.Customer));
            if (_useraccount != null && _useraccount.CEID > 0)
            {
                _userId = _useraccount.CEID;
                Profile _userprofile = new Profile();
                ProfileDB _userprofiledb = new ProfileDB();

                Contact _usercontact = new Contact();
                ContactDB _usercontactdb = new ContactDB();

                Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                _userprofile = _userprofiledb.GetProfile(_useraccount.CEID);

                if (_userprofile != null && _userprofile.ProfileId > 0)
                {
                    _userprofile.SurName = string.Empty;
                    _userprofile.FirstName = Server.HtmlEncode(txtName.Text);
                    _userprofile.IsAcceptTC = checkIsAgreement.Checked;
                    _userprofiledb.Insert(_userprofile);
                }
                _usercontact = _usercontactdb.GetContact(_useraccount.CEID);
                if (_usercontact != null && _usercontact.ContactId > 0)
                {
                    _usercontact.Mobile = txtMobile.Text.Trim();
                    _usercontactdb.Insert(_usercontact);
                }
                Session[CE.Global.General.UserId] = _useraccount.CEID;
                Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                Session[CE.Global.General.UserEmail] = _useraccount.Email;
                Session[CE.Global.General.UserName] = _userprofile.FirstName;
                Session[CE.Global.General.IsAcceptTC] = "0";
                if (_userprofile.IsAcceptTC == true)
                {
                    Session[CE.Global.General.IsAcceptTC] = "1";
                }
                Session[CE.Global.General.UserPhoneNo] = _usercontact.Mobile;
                _useraccount = null;
                _useraccountdb = null;
                _userprofile = null;
                _userprofiledb = null;
                _usercontact = null;
                _usercontactdb = null;
            }
            else
            {
                if (UpdateProfile(_userId, 0) > 0)
                {
                    SendMailToUser(EmailAddress, Name, MobileNumber); //txtEmailAddress.Text.Trim()

                    Session["CLASSTYPE"] = "1";
                    ScriptManager.RegisterStartupScript(Page, this.GetType(), "alertThxU", "alert('Saved successfully!');", true);
                    _userId = Convert.ToInt64(Session[General.UserId].ToString());
                }
            }
            SetCookies(Session[CE.Global.General.UserName].ToString(), Session[CE.Global.General.UserEmail].ToString(), Session[CE.Global.General.UserPhoneNo].ToString());
            #endregion

            UserSIR _usersir = new UserSIR();
            UserSIRDB _usersirdb = new UserSIRDB();
            _usersir = _usersirdb.GetSIR(txtEmail.Text.Trim(), txtMobile.Text.Trim());
            if (_usersir == null)
            {
                _usersir = new UserSIR();
                _usersir.SIRID = 0;
                _usersir.FullName = txtName.Text;
                _usersir.Email = txtEmail.Text;
                _usersir.MobileNumber = txtMobile.Text;
                _usersir.CarRenewalMonth = Convert.ToInt16(ddlCarMonth.Text);
                _usersir.Status = true;

                if (Session["Language"].ToString() == "en-US")
                {
                    _usersir.IsEnglish = 1;
                }
                else
                {
                    _usersir.IsEnglish = 0;
                }
                _usersir.SIRID = _usersirdb.Insert(_usersir);

                if (_usersir.SIRID > 0)
                {
                    string _emailTo = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.SIRMessageReceiver");
                    string _emailBody = "<br/><table><tr><td>" + Resources.CarInsurance.FullName + "</td><td>:</td><td>" + txtName.Text + "</td></tr>";
                    _emailBody += "<tr><td>" + Resources.CarInsurance.EmailAddress + "</td><td>:</td><td>" + txtEmail.Text + "</td></tr>";
                    _emailBody += "<tr><td>" + Resources.CarInsurance.MobileNo + "</td><td>:</td><td>" + txtMobile.Text + "</td></tr>";
                    _emailBody += "<tr><td>" + Resources.CarInsurance.RenewalMonth + "</td><td>:</td><td>" + ddlCarMonth.SelectedItem.Text + "</td></tr></table><br/><br/>";
                    _emailBody += Resources.WelcomeEmail.Thankyou;
                    CE.Mail.MyMailManager.SendCRMMessage(_emailTo, "Car Insurance Reminder (" + txtName.Text + ")", _emailBody);
                }
                else
                {
                    lblSetInsMessage.Visible = true;
                    lblSetInsMessage.Text = Resources.CarInsurance.TransactionFaild;// "Transaction failed. Please try again later.";
                }
            }
            else
            {
                _usersir.FullName = txtName.Text;
                _usersir.CarRenewalMonth = Convert.ToInt16(ddlCarMonth.Text);
                if (Session["Language"].ToString() == "en-US")
                {
                    _usersir.IsEnglish = 1;
                }
                else
                {
                    _usersir.IsEnglish = 0;
                }
                _usersir.SIRID = _usersirdb.Insert(_usersir);
            }

            if (_usersir != null && _usersir.SIRID > 0)
            {
                lblSetInsMessage.Visible = true;
                lblSetInsMessage.Text = Resources.CarInsurance.ReminderSuccesfulMessage;

                txtName.Text = "";
                txtEmail.Text = "";
                txtMobile.Text = "";
                ddlCarMonth.SelectedValue = "-1";

                txtName.ReadOnly = true;
                txtEmail.ReadOnly = true;
                txtMobile.ReadOnly = true;
                txtName.Enabled = false;
                txtEmail.Enabled = false;
                txtMobile.Enabled = false;
                ddlCarMonth.Enabled = false;
                btnSetReminder.Enabled = false;
                string _redirectUrl = CE.Global.General.GetUrl("~/user/user-message", Page);
                Session["UMMSG"] = "UMG,912";
                Response.Redirect(_redirectUrl);
            }
            else
            {
                lblSetInsMessage.Visible = true;
                lblSetInsMessage.Text = Resources.CarInsurance.TransactionFaild;//"Transaction failed. Please try again later.";
            }
        }
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        txtName.Text = HttpUtility.HtmlEncode(txtName.Text);
        txtEmail.Text = HttpUtility.HtmlEncode(txtEmail.Text);
        txtMobile.Text = HttpUtility.HtmlEncode(txtMobile.Text);
        
        #region Customer

        //Email
        if (rfvName.Enabled && rfvName.ValidationGroup == strValidationGroup)
        {
            rfvName.Validate();
            if (rfvName.IsValid == false)
            {
                txtName.ControlStyle.CssClass = "input-fields validationError";
            }
            else
            {
                txtName.ControlStyle.CssClass = "input-fields";
            }
        }
        else
        {
            txtName.ControlStyle.CssClass = "input-fields";
        }

        if (revName.Enabled && revName.ValidationGroup == strValidationGroup)
        {
            if (rfvName.IsValid)
            {
                revName.Validate();
                if (revName.IsValid == false)
                {
                    txtName.ControlStyle.CssClass = "input-fields validationError";
                }
                else
                {
                    txtName.ControlStyle.CssClass = "input-fields";
                }
            }
        }
        else
        {
            txtName.ControlStyle.CssClass = "input-fields";
        }

        //Email
        if (rfvEmail.Enabled && rfvEmail.ValidationGroup == strValidationGroup)
        {
            rfvEmail.Validate();
            if (rfvEmail.IsValid == false)
            {
                txtEmail.ControlStyle.CssClass = "input-fields validationError";
            }
            else
            {
                txtEmail.ControlStyle.CssClass = "input-fields";
            }
        }
        else
        {
            txtEmail.ControlStyle.CssClass = "input-fields";
        }

        if (revEmail.Enabled && revEmail.ValidationGroup == strValidationGroup)
        {
            if (rfvEmail.IsValid)
            {
                revEmail.Validate();
                if (revEmail.IsValid == false)
                {
                    txtEmail.ControlStyle.CssClass = "input-fields validationError";
                }
                else
                {
                    txtEmail.ControlStyle.CssClass = "input-fields";
                }
            }
        }
        else
        {
            txtEmail.ControlStyle.CssClass = "input-fields";
        }

        //MobileNo
        if (rfvMobile.Enabled && rfvMobile.ValidationGroup == strValidationGroup)
        {
            rfvMobile.Validate();
            if (rfvMobile.IsValid == false)
            {
                txtMobile.ControlStyle.CssClass = "input-fields validationError";
            }
            else
            {
                txtMobile.ControlStyle.CssClass = "input-fields";
            }
        }
        else
        {
            txtMobile.ControlStyle.CssClass = "input-fields";
        }

        if (revMobile.Enabled && revMobile.ValidationGroup == strValidationGroup)
        {
            if (rfvMobile.IsValid)
            {
                revMobile.Validate();
                if (revMobile.IsValid == false)
                {
                    txtMobile.ControlStyle.CssClass = "input-fields validationError";
                }
                else
                {
                    txtMobile.ControlStyle.CssClass = "input-fields";
                }
            }
        }
        else
        {
            txtMobile.ControlStyle.CssClass = "input-fields";
        }

        //CarMonth
        if (rfvCarMonth.Enabled && rfvCarMonth.ValidationGroup == strValidationGroup)
        {
            rfvCarMonth.Validate();
            if (rfvCarMonth.IsValid == false)
            {
                ddlCarMonth.ControlStyle.CssClass = "input-fields-dropdown validationError";
            }
            else
            {
                ddlCarMonth.ControlStyle.CssClass = "input-fields-dropdown";
            }
        }
        else
        {
            ddlCarMonth.ControlStyle.CssClass = "input-fields-dropdown";
        }

        #endregion

    }

    #region Customer

    private Int64 UpdateProfile(Int64 UserId, Int64 CarId)
    {
        Int64 _retValue = 0;

        if (UserId != 0)
        {
            Profile _profile = new Profile();
            ProfileDB _profiledb = new ProfileDB();

            Contact _contact = new Contact();
            ContactDB _contactdb = new ContactDB();

            _profile = _profiledb.GetProfile(UserId);
            _contact = _contactdb.GetContact(UserId);
            _retValue = UserId;
            if (_profile != null)
            {
                #region Update Profile

                _profile.Salutation = "";
                txtName.Text = CE.Global.General.ClearScriptTag(txtName.Text.Trim());
                _profile.FirstName = HttpUtility.HtmlEncode(txtName.Text);
                _profile.SurName = "";
                if (_profile.DOB.Year == 1900)
                {
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _profile.DOB = dteDOB;
                }
                if (_profile.Gender.ToString().Trim() == "")
                {
                    _profile.Gender = 'M';
                }
                _profile.Status = "Complete";
                _profile.IsAcceptTC = checkIsAgreement.Checked;

                _retValue = _profiledb.Insert(_profile);

                if (_retValue > 0 && _contact != null)
                {
                    _contact.Mobile = txtMobile.Text.Trim();
                    _contact.Status = true;

                    _retValue = _contactdb.Insert(_contact);
                }

                if (_retValue > 0)
                {
                    if (_profile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = _profile.FirstName + " " + _profile.SurName;
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = _profile.SurName;
                    }
                    Session[CE.Global.General.IsAcceptTC] = "0";
                    if (_profile.IsAcceptTC == true)
                    {
                        Session[CE.Global.General.IsAcceptTC] = "1";
                    }
                    if (_contact != null)
                    {
                        Session[General.UserPhoneNo] = _contact.Mobile;
                    }
                    Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                    if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) == Convert.ToInt32(CE.Global.CEUserType.Provider))
                    {
                        Session[CE.Global.General.ProviderProfileFirstTime] = "0";
                    }
                }

                _profile = null;
                _contact = null;
                #endregion
            }
        }
        else
        {
            _retValue = SaveNewCustomer();
            UserId = _retValue;
        }
        return _retValue;
    }

    private Int64 SaveNewCustomer()
    {
        #region New Customer
        Int64 _retVal = 0;
        if (Page.IsValid)
        {

            Account _useraccount = new Account();
            AccountDB _useraccountdb = new AccountDB();

            Profile _userprofile = new Profile();
            ProfileDB _userprofiledb = new ProfileDB();

            Contact _contact = new Contact();
            ContactDB _contactdb = new ContactDB();

            _useraccount = _useraccountdb.GetUserAccount(txtEmail.Text.Trim(), Convert.ToInt32(CE.Global.CEUserType.Customer));
            //_useraccount = _useraccountdb.GetUserAccount(txtEmail.Text.Trim(), txtMobile.Text.Trim().ToLower(), Convert.ToInt32(CE.Global.CEUserType.Customer));
            if (_useraccount != null)
            {
                if (_useraccount.CEID > 0)
                {
                    _retVal = _useraccount.CEID;
                    _contact = _contactdb.GetContact(_useraccount.CEID);
                    Session[CE.Global.General.UserId] = _useraccount.CEID;
                    Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                    Session[CE.Global.General.UserEmail] = _useraccount.Email;
                    Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                    Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                    _userprofile = _userprofiledb.GetProfile(_useraccount.CEID);
                    if (_userprofile != null && _userprofile.ProfileId > 0)
                    {
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                    }
                }
            }
            else
            {

                long _result = -1;
                _useraccount = new Account();
                _useraccount.Email = txtEmail.Text.Trim().ToLower();
                string _authcode = txtMobile.Text.Trim();
                _useraccount.AuthCode = _authcode;
                _useraccount.UserId = "CEUSERAUTOIDCI";
                _useraccount.UserTypeId = Convert.ToInt32(CE.Global.CEUserType.Customer);
                _useraccount.IsAcceptTC = false;
                _useraccount.Status = true;
                _useraccount.RefCEUserID = -1;
                _result = _useraccountdb.Insert(_useraccount);
                _useraccount.CEID = _result;
                _retVal = _useraccount.CEID;
                if (_result > 0)
                {
                    _userprofile.Salutation = "";
                    _userprofile.FirstName = Server.HtmlEncode(txtName.Text);
                    _userprofile.SurName = "";
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _userprofile.DOB = dteDOB;
                    _userprofile.Gender = 'M';

                    _userprofile.Occupation = Convert.ToInt32("54");
                    _userprofile.Status = "Complete";
                    _userprofile.RefCEUserId = _useraccount.CEID;
                    _userprofile.IsAcceptTC = checkIsAgreement.Checked;
                    _result = _userprofiledb.Insert(_userprofile);

                    _contact.Email = _useraccount.Email;
                    _contact.Mobile = txtMobile.Text.Trim();

                    _contact.Status = true;
                    _contact.RefCEUserId = _useraccount.CEID;
                    _result = _contactdb.Insert(_contact);

                    if (_result > 0)
                    {
                        Session[CE.Global.General.UserId] = _useraccount.CEID;
                        Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                        Session[CE.Global.General.UserEmail] = _useraccount.Email;
                        Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                        Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                        Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                        Session[CE.Global.General.IsAcceptTC] = "0";
                        if (_userprofile.IsAcceptTC == true)
                        {
                            Session[CE.Global.General.IsAcceptTC] = "1";
                        }
                    }

                }

            }
        }
        else
        {
            _retVal = 0;
        }

        return _retVal;
        #endregion
    }

    private bool SendMailToUser(string EmailAddress, string UserName, string AuthCode)
    {
        bool _retVal = false;
        _retVal = CE.Email.Welcome.SendMail(EmailAddress, UserName, AuthCode);
        return _retVal;
    }

    private string EmailAddress
    {
        get { return txtEmail.Text.Trim(); }
    }

    private string MobileNumber
    {
        get { return txtMobile.Text.Trim(); }
    }

    private string Name
    {
        get { return txtName.Text.Trim(); }
    }

    private void SetCookies(string Name, string Email, string Mobile)
    {
        try
        {
            HttpCookie _cookie = new HttpCookie("GGQuote");
            _cookie.Values.Add("CustomerName", MySecurity.Encrypt(Name, true));
            _cookie.Values.Add("CustomerEmail", MySecurity.Encrypt(Email, true));
            _cookie.Values.Add("CustomerMobile", MySecurity.Encrypt(Mobile, true));

            _cookie.Expires = DateTime.Now.AddDays(60);
            Response.Cookies.Add(_cookie);
        }
        catch (Exception Ex)
        {
            Ex = null;
        }
    }

    private void GetCookies()
    {
        try
        {
            HttpCookie _cookie = Request.Cookies.Get("GGQuote");
            if (_cookie != null)
            {
                txtName.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerName"), true);
                txtEmail.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerEmail"), true);
                string _mobile = MySecurity.Decrypt(_cookie.Values.Get("CustomerMobile"), true);
                txtMobile.Text = _mobile;
                //txtEmail.ReadOnly = true;
            }
        }
        catch (Exception Ex)
        {
            Ex = null;
        }
    }

    #endregion

}
